package com.zut.service.impl;

import com.zut.dao.UserDao;
import com.zut.domain.User;
import com.zut.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;




/**
 * @author DingTian
 * @version 1.0
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserDao userDao;

    @Autowired
    private ThingsBoardService thingsBoardService;


    @Value("${spring.thingsboard.url}")
    String host ;

    @Override
    public boolean insert(User user) throws Exception {
        thingsBoardService.createDevice(user.getId());
        user.setGrant(thingsBoardService.getDeviceToken(user.getId()));




        String url = host+"/api/v1/"+thingsBoardService.getDeviceToken(user.getId())+"/attributes";
        String postData = "{\"temperature\": 2,\"humidity\": 2,\"distance\": 2}";

        // 创建URL对象
        URL obj = new URL(url);

        // 创建HttpURLConnection对象
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // 设置请求方法为POST
        con.setRequestMethod("POST");

        // 允许输入输出流
        con.setDoOutput(true);
        con.setDoInput(true);

        // 设置请求头信息
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("charset", "utf-8");

        // 设置请求体数据
        byte[] postDataBytes = postData.getBytes(StandardCharsets.UTF_8);
        con.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
        con.getOutputStream().write(postDataBytes);

        // 发送请求并获取响应
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine).append("\n");
        }
        in.close();

        return userDao.insert(user) > 0;
    }

    @Override
    public User selectOneUser(String id) {
        return userDao.selectOneUser(id);
    }


    @Override
    public List<String> selectAllToken() {
        return userDao.selectAllToken();
    }
}
